package com.scott.crm.user.controller;

import com.scott.crm.base.bean.Data;
import com.scott.crm.base.dto.RedisDTO;
import com.scott.crm.base.utils.DataUtil;
import com.scott.crm.base.service.ScottRedisService;
import com.scott.crm.base.utils.TokenUtil;
import com.scott.crm.role.bean.RoleBean;
import com.scott.crm.user.bean.UserBean;
import com.scott.crm.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author 黄后林
 * @version 1.0
 * @note
 * @date 2021-12-04 13:55:09
 */
@CrossOrigin
@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private ScottRedisService scottRedisService;


    @RequestMapping(value = "/user/{userId}",method = RequestMethod.GET)
    public Data findRoleById(@PathVariable("userId") Integer id, HttpServletRequest request){

        String token= request.getHeader("token");

        if("".equals(token)){
            return DataUtil.errors();
        }

        RedisDTO dto = ScottRedisService.REDIS.get(token);
        return DataUtil.success(dto);

    }

    /**
     * 方法描述: 登陆的逻辑
     * @author: 黄后林
     * @date: 2021/12/4 23:00
     * @param userBean
     * @return com.scott.crm.base.bean.Data
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public Data login(@RequestBody UserBean userBean) {
        if(null == userBean){
            //如果没有提交phone和password 直接返回错误 避免空指针异常
            return DataUtil.errors();
        }
        log.info(userBean.toString());
        UserBean user = userService.login(userBean);
        if(user != null){
            //说明使用phone和password匹配到1个用户 登录成功

            System.out.println("------------------登录成功------------------");
            //token只要保证唯一就行 可以随便写
            String token = TokenUtil.generateToken();
            System.out.println("-----------登录成功后的token=["+token+"]-----------");

            //把token放入redis中
            scottRedisService.saveTokenToRedis(token,user);
            return DataUtil.success(token);
        }
        return null;
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public Data logout(HttpServletRequest request) {

        String token= request.getHeader("token");
        if("".equals(token) || "null".equals(token)){

            //说明已经点击过注销
            return DataUtil.logOutSuccess();
        }

        ScottRedisService.REDIS.remove(token);
        return DataUtil.success(token);
    }
}

